using System;
using UnityEngine;

/// <summary>
/// 物理OnTriggerEnter封装
/// </summary>
public class TriggerEnterWrap : MonoBehaviour
{
    private new Collider collider;

    public Collider Collider
    {
        get
        {
            if (collider == null) collider = GetComponent<Collider>();
            return collider;
        }
        set => collider = value;
    }

    public Action<Collider> Func;

    public event Action<Collider> Event;

    private void OnTriggerEnter(Collider other)
    {
        if (!enabled) return;
        Func?.Invoke(other);
        Event?.Invoke(other);
    }

    /// <summary>
    /// 获取组件（若不存在则添加）
    /// </summary>
    /// <param name="obj">物体对象</param>
    /// <param name="func">回调函数</param>
    /// <returns></returns>
    public static TriggerEnterWrap Get(GameObject obj, Action<Collider> func = null)
    {
        var wrap = obj.GetComponent<TriggerEnterWrap>();
        if (wrap == null) wrap = obj.AddComponent<TriggerEnterWrap>();
        if (func != null) wrap.Func = func;
        return wrap;
    }
}